package com.bs.visitservice.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.bs.visitservice.cache.impl.JedisLoginCache;
import com.bs.visitservice.entity.CommentPhoto;
import com.bs.visitservice.entity.SellerPhotos;
import com.bs.visitservice.entity.UserInfo;
import com.bs.visitservice.service.CommentPhotoService;
import com.bs.visitservice.service.SellerPhotosService;
import com.bs.visitservice.service.UserInfoService;
import com.bs.visitservice.utils.JwtUtil;
import com.bs.visitservice.utils.Md5Utils;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.WechatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户一键登陆
 */
@RestController
@ConfigurationProperties(prefix = "wx")
public class LoginController {

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    private String appId;
    private String secret;
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private SellerPhotosService sellerPhotosService;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JedisLoginCache jedisCacheManager;
    @Autowired
    private CommentPhotoService commentPhotoService;
    @RequestMapping(value="/userpublic/login",method = RequestMethod.GET)
    public Result login(HttpServletRequest request){
        System.out.println(appId+";"+secret);
        String code = request.getParameter("code");
        String encryptData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        if(code == null || encryptData == null || iv == null){
            logger.info("【code="+code+",encryptedData="+encryptData+",iv="+iv);
            Result.error("参数缺失!");
        }
        logger.info("【code="+code+",encryptedData="+encryptData+",iv="+iv);
        String res = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code", String.class);
        logger.info("【res="+res+"】");
        JSONObject jsonObject = JSONObject.parseObject(res);
        Map<String,Object> resMap = (Map<String,Object>)jsonObject;
        logger.info((String)resMap.get("session_key"));
        String decryptData = WechatUtil.decryptData(encryptData, (String) resMap.get("session_key"), iv);
        Map<String,Object> decryptDataMap = (Map<String,Object>)JSONObject.parseObject(decryptData);
        System.out.println(decryptDataMap);
        String nickName = (String)decryptDataMap.get("nickName");
        String avatarUrl = (String)decryptDataMap.get("avatarUrl");
        String openid = (String)resMap.get("openid");
        List<UserInfo> userInfo = userInfoService.lambdaQuery().eq(UserInfo::getOpenid, openid).list();
        if(userInfo.size()<=0){
            UserInfo uf = new UserInfo();
            uf.setNickname(nickName);
            uf.setOpenid(openid);
            uf.setStatus("0");
            uf.setAvatarUrl(avatarUrl);
            userInfoService.save(uf);
            userInfo = userInfoService.lambdaQuery().eq(UserInfo::getOpenid,openid).list();
        }
        String tokenId = null;
        if(userInfo.size() > 0){
            UserInfo curUser = userInfo.get(0);
            if(!"0".equals(curUser.getStatus())){
               return Result.error("账号已被封禁！");
            }
            curUser.setAvatarUrl(avatarUrl);
            userInfoService.updateById(curUser);
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR,1);
            Map<String,Object> claims = new HashMap<>();
            claims.put("loginNo",curUser.getNo());
            claims.put("role","user");
            tokenId = JwtUtil.genToken(claims,c.getTime());
            //小程序端失效时间10小时
            jedisCacheManager.putCache(tokenId, curUser.getNo(), 10*3600);
        }
        List<Map<String,Object>> data = new ArrayList<>();
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("tokenId", tokenId);
        data.add(dataMap);
        return Result.success(data);
    }

    @RequestMapping(value = "/userpublic/getImage",method = RequestMethod.GET)
    public Result getImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream is =  this.getClass().getResourceAsStream("/static/images/5a1e5039e0a1f.jpg");
        //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode("5a1e5039e0a1f.jpg", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = is.read(bytes))>0){
            //outputStream.write(bytes,0,len);
            bos.write(bytes, 0,len);
        }
        byte[] res = bos.toByteArray();

        is.close();

/*
    SellerPhotos sp = new SellerPhotos();
        sp.setNo(123l);
        sp.setDescri("测试图片");
        sp.setPhotoType(1);
        sp.setRemark("测试备注");
        sp.setSellerNo(123l);
        sp.setSn(1);
        sp.setPhoto(res);
        sellerPhotosService.save(sp);
*/
       // List<SellerPhotos> resList = sellerPhotosService.lambdaQuery().list();
        List<CommentPhoto> resList = commentPhotoService.lambdaQuery().list();
        return Result.success(resList);
       /* resList.forEach(r->{
            try {
                outputStream.write(r.getPhoto());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });*/

       // outputStream.close();
    }
}
